import React, { useRef, useState } from "react"

interface DraggableColumnProps {
	id: string
	index: number
	fixed: boolean
	onDrag: (sourceIndex: number, destinationIndex: number) => void
	children: React.ReactNode
}

const DraggableColumn: React.FC<DraggableColumnProps> = ({ id, index, fixed, onDrag, children }) => {
	const [dragging, setDragging] = useState<boolean>(false)
	const dragRef = useRef<HTMLDivElement>(null)

	const handleDragStart = (e: React.DragEvent<HTMLDivElement>) => {
		setDragging(true)
		e.dataTransfer.setData("text/plain", String(index))
	}

	const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault()
	}

	const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault()
		setDragging(false)
		const sourceIndex = Number(e.dataTransfer.getData("text/plain"))
		const destinationIndex = index
		if (sourceIndex !== destinationIndex && onDrag) {
			onDrag(sourceIndex, destinationIndex)
		}
	}

	return (
		<span
			ref={dragRef}
			draggable
			onDragStart={handleDragStart}
			onDragOver={handleDragOver}
			onDrop={handleDrop}
			style={{ cursor: fixed ? "no-drop" : "move", opacity: dragging ? 0.5 : 1 }}
			key={id}
		>
			{children}
		</span>
	)
}

export default DraggableColumn
